package com.m3839.sdk.pay.task;

import android.app.Activity;
import android.os.Handler;
import android.os.Looper;

import com.m3839.sdk.common.core.ApiError;
import com.m3839.sdk.common.core.Constant;
import com.m3839.sdk.common.event.SubjectBus;
import com.m3839.sdk.common.util.LogUtils;
import com.m3839.sdk.common.util.ToastUtil;
import com.m3839.sdk.login.bean.InternalTip;
import com.m3839.sdk.login.core.LoginManager;
import com.m3839.sdk.login.ui.controller.ILoginUiController;
import com.m3839.sdk.login.ui.controller.LoginUiControllerImpl;
import com.m3839.sdk.pay.bean.PayConfig;
import com.m3839.sdk.pay.bean.PayInfo;
import com.m3839.sdk.pay.bean.PayResult;
import com.m3839.sdk.pay.listener.HykbPayListener;
import com.m3839.sdk.pay.model.IPayModel;
import com.m3839.sdk.pay.model.PayApiModel;
import com.m3839.sdk.pay.ui.controller.IPayUiController;
import com.m3839.sdk.pay.ui.controller.PayUiControllerImpl;

import java.util.Observable;
import java.util.Observer;
import java.util.concurrent.atomic.AtomicBoolean;

/**
 * @author ChenBaoyang
 * @description: IPayTask
 * @date 2021/12/9 09:52
 */
public class PayTask {

    /** activity对象，用来调用UI弹窗 */
    protected Activity activity;

    /** 支付下单信息（游戏订单，金额，商品名称，游戏服ID，透传字段） */
    protected PayInfo payInfo;

    /** 配置信息（游戏币名称，充值比例，充值方式等） */
    protected PayConfig payConfig;

    /** 登录模块涉及到的UI界面控制器 */
    private final ILoginUiController loginUiController;

    /** 支付模块涉及到的UI界面控制器 */
    protected final IPayUiController payUiController;

    /** 支付模块涉及的数据源 */
    protected final IPayModel payModel;

    /** 用来判断是否在支付流程中 */
    private final AtomicBoolean isPaying = new AtomicBoolean(false);

    /** 支付回调，用来回调给游戏方 */
    private HykbPayListener listener;

    /** 轮询任务栈 */
    private IPollingTask pollingTask;


    public PayTask(Activity activity, PayInfo payInfo, HykbPayListener listener) {

        this.activity = activity;
        this.payInfo = payInfo;
        this.listener = listener;

        loginUiController = new LoginUiControllerImpl();
        payUiController = new PayUiControllerImpl();
        payModel = new PayApiModel();

        observeModelEvent();
    }

    /**
     * 开始执行支付流程
     */
    public void startPay() {
        isPaying.set(true);
        //先调支付配置，获取支付配置
        payModel.loadPayConfig();
    }

    /**
     * 监听支付配置拉取的事件
     */
    private void observeModelEvent() {
        // 监听支付配置加载成功后的事件
        SubjectBus.get().observe(Constant.HYKB_EVENT_PAY_CONFIG, new Observer() {
            @Override
            public void update(Observable o, Object arg) {
                payConfig = (PayConfig) arg;
                payUiController.showPayDialog(activity, PayTask.this, payInfo, payConfig);
            }
        });

        // 监听支付配置加载失败后的事件
        SubjectBus.get().observe(Constant.HYKB_EVENT_PAY_CONFIG_FAILED, new Observer() {
            @Override
            public void update(Observable o, Object arg) {
                resetPayFlag();
                ApiError apiError = (ApiError) arg;
                if(apiError == null) {
                    return;
                }
                int code = apiError.code;
                String message = apiError.message;
                if (code == Constant.HYKB_CODE_PAY_MAINTENANCE ||
                        code == Constant.HYKB_CODE_PAY_CLOSE) {
                    //支付方式维护中
                    ToastUtil.showToast(activity, message);
                    PayResult result = new PayResult();
                    result.payInfo = payInfo;
                    result.resultCode = code;
                    result.message = message;
                    handlePayCallBack(result);
                } else if (code == Constant.HYKB_CODE_USER_ROBBED) {
                    //code : 2003 表示用户被抢登
                    handleUserRobbed(message);
                } else {
                    PayResult result = new PayResult();
                    result.payInfo = payInfo;
                    result.resultCode = code;
                    result.message = message;
                    handlePayCallBack(result);
                    LogUtils.flog(apiError.toString());
                }
            }
        });

    }

    /**
     * 表示是否处于支付流程中
     * @return
     */
    public boolean isPaying(){
        return isPaying.get();
    }

    /**
     * 充值支付状态
     */
    public void resetPayFlag() {
        isPaying.set(false);
    }

    public void handlePayCallBack(PayResult result) {
        LogUtils.flog( "result = "+result.toString());
        resetPayFlag();
        if (listener != null) {
            listener.onPayResult(result.resultCode, result.message, result.payInfo);
        }
    }

    public void handPayCallBack(int code, String message) {
        resetPayFlag();
        if (listener != null) {
            listener.onPayResult(code, message, payInfo);
        }
    }

    /**
     * 支付的时候，提示账号被抢登了，弹出抢登弹窗
     * @param message
     */
    public void handleUserRobbed(String message) {
        resetPayFlag();
        LoginManager.getInstance().logout();
        InternalTip tip = InternalTip.getLoginAgainTip(message);
        loginUiController.showLoginTipDialog(activity, tip);
    }

    public IPayModel getPayModel() {
        return payModel;
    }

    public IPayUiController getPayUiController() {
        return payUiController;
    }

    public void showPayResultDialog(PayResult payResult) {
        payUiController.showPayResultDialog(activity, this, payConfig, payResult);
    }

    public void startPollingOrder(String orderId) {
        if(pollingTask == null) {
            pollingTask = new PayOrderPollingTask(this, orderId);
        }
        pollingTask.startPollingOrder();
    }
}
